import _ from 'lodash'
import React from 'react'
import { useLayoutEffect } from 'react'
import {
  View,
  Text,
  FlatList,
  SectionList,
  Image,
  TouchableOpacity
} from 'react-native'

import { toJS } from 'mobx'
import { observer, useLocalObservable, Observer } from 'mobx-react-lite'

import { Placeholder, PlaceholderLine, PlaceholderMedia, Shine } from 'rn-placeholder'
import { useStores } from '../stores'
import i18n from '../i18n'
import { BookItem, CollapsibleText, SubscribeButton, Snackbar } from '../views'
import { useNavigation } from '@react-navigation/native'
import Spinner from 'react-native-spinkit'

const PlaceholderItem = observer(() => {
  return (
    <Placeholder
      Animation={Shine}
      Left={PlaceholderMedia}
    >

      <PlaceholderLine width={30} />
      <PlaceholderLine width={60} />
      <PlaceholderLine />
    </Placeholder>
  )
})

const PlaceholderList = observer(({ count, data }) => {

  const { appearance: ap } = useStores()
  return (
    <View style={{
      flex: 1,
      backgroundColor:
        ap.theme.background,
      paddingTop: 24, paddingLeft: 12, paddingRight: 12
    }}>
      <Title data={data} />
      {
        _.range(0, count).map(v => <PlaceholderItem key={Math.random()} />)
      }
    </View>
  )
})

const Title = ({ data }) => {
  const { appearance: ap } = useStores()
  return (
    <View style={{ borderColor: ap.theme.tiny, borderBottomWidth: 1, paddingBottom: 12, paddingRight: 12 }}>
      <View style={{ ...styles.titleContainer }}>
        <Text style={{ ...styles.title, color: ap.theme.primary }}>{data.name}</Text>
        <Text style={{ color: ap.theme.second, fontSize: 12, fontWeight: 'bold' }}>•{data.count}{i18n.t('hasBook')}</Text>
        <View style={{ flex: 1, alignItems: 'flex-end' }}>
          <SubscribeButton title={i18n.t('subscribe')} />
        </View>
      </View>
      {
        data.info ?
          <View style={{ paddingTop: 6 }}>
            <CollapsibleText
              style={{ color: ap.theme.second }}
              numberOfLines={4}
              labels={[i18n.t('expand'), i18n.t('collapse')]}>
              {data.info}
            </CollapsibleText>
          </View> : <></>
      }
    </View>
  )
}

export default observer(({ navigation, route }) => {
  const { data, key } = route.params
  const { appearance: ap, bookApi } = useStores()
  const api = key == 'category' ? bookApi.fetchBooksByCategory : bookApi.fetchBooksByAuthor

  useLayoutEffect(() => {
    navigation.setOptions({ title: data.name })
  })

  const count = 7
  const states = useLocalObservable(() => ({
    books: [],
    loading: true,
    hasMore: true,
    start: 0, //request remote page index
    appendBooks(books) {
      this.books = _.concat(this.books, books)
    },
    setData(data) {
      console.log(data, 'List')
      this.hasMore = data.books.length >= count
      //[0] = title info
      const title = _.omit(data, ['books'])
      title.isTitle = true
      this.books = [title, ...data.books]
    },
    setLoading(isLoading) {
      this.loading = isLoading
    },
    setHasMore(more) {
      this.hasMore = more
    }
  }))

  const onScroll = e => {
    if (!states.hasMore || states.loading) return
    const offsetY = e.nativeEvent.contentOffset.y
    const oriageScrollHeight = e.nativeEvent.layoutMeasurement.height
    const contentSizeHeight = Math.round(e.nativeEvent.contentSize.height)
    if (Math.round(offsetY + oriageScrollHeight) >= contentSizeHeight) {
      if (!states.loading) {
        states.setLoading(true)
        states.start += 1
        //most for 20 pages
        if (states.start > 20) {
          states.setHasMore(false)
          return
        }
        api(data._id, 1, states.start * count, count).then(
          data => {
            states.setLoading(false)
            if (data[key].books.length) {
              states.appendBooks(data[key].books)
            } else {
              states.setHasMore(false)
            }
          }
        )
      }
    }
  }

  if (!states.books.length) {
    api(data._id, 1, states.start, count).then(
      data => {
        states.setData(data[key])
        states.setLoading(false)
      }
    ).catch(err => {
      console.log("Error", err.toString())
      Snackbar.error({ text: err.toString(), statusBarBackgroundColor: ap.theme.background })
    })
    return <PlaceholderList count={2} data={data} />
  }

  const renderItem = ({ item }) => {
    item = toJS(item)
    //first item is title detail
    if (item.isTitle) return <Title data={item} />
    //books
    return <BookItem book={item} needButton={true} />
  }

  return (
    <Observer>
      {
        () => (
          <View style={{ ...styles.container, backgroundColor: ap.theme.background }}>

            {<FlatList
              data={states.books}
              renderItem={renderItem}
              keyExtractor={it => it._id}
              onScroll={onScroll}
              scrollIndicatorInsets={{ right: 1 }}
            />}


            {
              states.loading ?
                <View
                  style={{
                    position: 'absolute', bottom: 0
                  }}>
                  <Spinner
                    isVisible={states.loading}
                    color={ap.theme.second}
                    type='Circle' size={24}
                  />
                </View>
                : <></>
            }
          </View>
        )
      }
    </Observer>
  )
})

const styles = {
  container: {
    flex: 1,
    paddingLeft: 12,
    // paddingRight: 12,
  },

  titleContainer: {
    paddingTop: 12,
    flexDirection: 'row',
    alignItems: 'center',
  },

  title: {
    fontSize: 18,
    fontWeight: 'bold',
  },

  bookTitle: {
    fontWeight: 'bold',
    fontSize: 14,
  },
}